<template>
  <div>
    <div class="player-container-wrap">
      <div>
        <video src="@/assets/video/wuting.mp4" ref="XPlayerRef"></video>
      </div>
      <div class="player-bas-dm-wrap" ref="baseBarrageRef"></div>
    </div>
    <div>
      <button @click="handleStart">开始</button>
      <button @click="handlePause">暂停</button>
    </div>
  </div>
</template>

<script setup>
import { ref, onUnmounted } from "vue";
const XPlayerRef = ref(null);
const baseBarrageRef = ref(null);
let timer = null;
let barrageMap = {}; //用于跟踪弹幕是否显示在屏幕上
let animationFrameId = null;
const barragePause = ref(false); // 控制弹幕暂停
const barragePauseMap = ref([]); // 保存暂停的动画

const barrageList = ref([
  {
    content: "好听",
    user: "lake",
    sendTime: "00.02",
    barrType: "base",
    position: 100, // 初始位置在弹幕容器外部
    animationPlayState: "paused", // 控制弹幕动画播放状态
  },
  {
    content: "好听啊",
    user: "lake",
    sendTime: "00.04",
    barrType: "base",
    position: 100, // 初始位置在弹幕容器外部
    animationPlayState: "paused", // 控制弹幕动画播放状态
  },
]);

const handleStart = () => {
  XPlayerRef.value.play();

  barrageList.value.forEach((barrage) => {
    barrage.animationPlayState = "running";
  });
  XPlayerRef.value.currentTime == 0 ? startBarrage() : resumeBarrages();
  console.log("开启弹幕");
};

const handlePause = () => {
  XPlayerRef.value.pause();
  pauseBarrages();
};

//创建弹幕
const startBarrage = () => {
  if (timer) return; //避免计时器重复设置
  timer = setInterval(() => {
    const videoElement = XPlayerRef.value; //获取当前播放器元素
    if (videoElement && videoElement.currentTime) {
      // 遍历弹幕列表，找出当前时间应该显示的弹幕
      for (let i = 0; i < barrageList.value.length; i++) {
        const barrage = barrageList.value[i];
        const sendTimeSeconds = timeStringToSeconds(barrage.sendTime);
        // 如果弹幕发送时间在当前视频时间之前且不在屏幕上，则创建弹幕
        if (
          sendTimeSeconds <= videoElement.currentTime &&
          !barrageMap[barrage.sendTime]
        ) {
          createBarrage(barrage);
          // 标记该弹幕已经在屏幕上 避免重复弹幕
          barrageMap[barrage.sendTime] = true;
        }
      }
    }
  }, 1000);
};

// 添加弹幕并调用动画方法
const createBarrage = (barrage) => {
  const barrageElement = document.createElement("div");
  barrage.element = barrageElement; // 将创建的弹幕元素赋值给barrage对象
  barrageElement.textContent = `${barrage.content}:${barrage.sendTime}`; //${barrage.user}:
  barrageElement.className = "barrage"; //直接引用弹幕样式未生效，目前用来起别名使用
  //直接给新建标签设置样式
  barrageElement.style.position = "absolute";
  barrageElement.style.whiteSpace = "nowrap";
  barrageElement.style.left = "100%";
  barrageElement.style.color = "#fff";
  barrageElement.style.top = `${Math.random() * 50}%`;
  barrageElement.style.animationPlayState = "running";
  //当新建弹幕元素加入基础弹幕容器中
  baseBarrageRef.value.appendChild(barrageElement);

  // 开始弹幕动画
  animateBaseBarrage(barrageElement);
};

// 基础弹幕调用函数
const animateBaseBarrage = (timestamp) => {
  const containerWidth = baseBarrageRef.value.offsetWidth;
  const moveStep = 1; // 弹幕移动的速度
  let start = null;
  if (!start) start = timestamp;

  const deltaTime = timestamp - start;
  const newLeft = 100 - deltaTime / 70; //控制弹幕速度，增加除数
  //如果当前暂停属性为false 则开始执行动画，动画从屏幕右侧被创建完开始加载
  barrageList.value.forEach((barrage) => {
    if (barrage.element) {
      if (barrage.animationPlayState === "running") {
        barrage.element.style.left = `${newLeft}%`;
        // barrage.position -= moveStep;
        // barrage.element.style.left = `${barrage.position}px`;
        if (
          newLeft <
          (-barrage.element.clientWidth / baseBarrageRef.value.offsetWidth) * 100
        ) {
          barrage.element.remove();
          // 可能还需要从barrageList中移除barrage对象
        }
      }
    }
  });
  //调用window api重绘动画
  animationFrameId = requestAnimationFrame(animateBaseBarrage);
};

// 暂停弹幕动画
const pauseBarrages = () => {
  barrageList.value.forEach((barrage) => {
    if (barrage.element) {
      barrage.element.style.animationPlayState = "paused";
    }
  });
  cancelAnimationFrame(animationFrameId);
};

// 继续弹幕动画
const resumeBarrages = () => {
  barrageList.value.forEach((barrage) => {
    if (barrage.element) {
      barrage.element.style.animationPlayState = "running";
    }
  });
  animationFrameId = requestAnimationFrame(animateBarrages);
};

// 将时间字符串转换为秒
const timeStringToSeconds = (timeString) => {
  const [minutes, seconds] = timeString.split(".");
  return parseInt(minutes, 10) * 60 + parseFloat(seconds);
};

onUnmounted(() => {
  cancelAnimationFrame(animationFrameId);
  // 清除所有弹幕动画
  // ...
});
</script>

<style lang="scss" scoped>
.player-container-wrap {
  position: relative;
  width: 100%; /* 视频容器宽度设置为100% */
  height: 100%; /* 视频容器高度设置为100% */
  min-width: 668px; /* 视频容器的最小宽度 */
  max-width: 1100px; /* 视频容器的最大宽度 */
  max-height: 572px; /* 视频容器的最大高度 */
  height: 572px;
  background: #000;

  video {
    position: absolute;
    content-visibility: visible;
    display: block;
    width: 100%; /* 视频宽度设置为100%，使其与容器宽度相同 */
    height: 100%; /* 视频高度设置为100%，使其与容器高度相同 */
    max-width: 100%; /* 确保视频的最大宽度不超过其容器 */
    max-height: 100%; /* 确保视频的最大高度不超过其容器 */
  }
}

.player-bas-dm-wrap {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow: hidden;
  pointer-events: none;
}

.barrage {
  animation: moveBarrage 10s linear infinite;
  z-index: 58;
}

@keyframes moveBarrage {
  from {
    left: 100%;
  }
  to {
    left: -100%;
  }
}
</style>
